package com.java1412.controller;

import com.java1412.entity.db1.Goods;
import com.java1412.entity.db2.User;
import com.java1412.service.GoodsService;
import com.java1412.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author java1412
 * @create 2021-07-07 17:00
 */

@RestController
public class TransactionController {
    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @Transactional(value = "jtaTransactionManager", rollbackFor = Exception.class)
    @GetMapping("/add")
    public ResponseEntity addTest() {
        Goods goods = new Goods();
        goods.setId(44L);
        goods.setName("iPhone 12");
        goodsService.addGoods(goods);

        User user = new User();
        user.setSex("男");
        user.setUsername("java1412");
        user.setAddress("南京");
        user.setBirthday(new Date());
        userService.addUser(user);
        return ResponseEntity.ok("添加成功");
    }

    // 在该接口中故意制造一个除以零的异常
    @Transactional(value = "jtaTransactionManager", rollbackFor = Exception.class)
    @GetMapping("/add2")
    public ResponseEntity addTest2() {
        Goods goods = new Goods();
        goods.setId(44L);
        goods.setName("iPhone 12");
        goodsService.addGoods(goods);

        User user = new User();
        user.setSex("男");
        user.setUsername("java1412");
        user.setAddress("南京");
        user.setBirthday(new Date());
        userService.addUser(user);
        int i = 1 / 0;
        System.out.println(i);
        return ResponseEntity.ok("添加失败");
    }
}
